package com.lzp.java.concurrent.lock.basemethod;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程等待Lock锁时是WAITING状态
 *
 * @author lzp
 * @date 2020/04/07
 */
public class LockRunnable implements Runnable {
    private final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        try {
            print();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void print() throws InterruptedException {
        final Lock lock = this.lock;
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName() + "打印任务");
            TimeUnit.SECONDS.sleep(10);
            System.out.println(Thread.currentThread().getName() + "打印完毕");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = new LockRunnable();
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        TimeUnit.SECONDS.sleep(1);
        thread2.start();
        TimeUnit.SECONDS.sleep(1);

        System.out.println(thread1.getName() + ":" + thread1.getState());
        System.out.println(thread2.getName() + ":" + thread2.getState());
    }
}
